<?php
set_include_path(PATH_SEPARATOR . dirname(dirname(__FILE__)) . 
				 PATH_SEPARATOR . dirname(dirname(dirname(__FILE__))) .
				 PATH_SEPARATOR . get_include_path());

include_once 'includes/connect.php';
include_once 'includes/models/Payment.php';

//
// Edit History:
//
//  Last $Author: munroe $
//  Last Modified: $Date: 2006/03/25 11:43:02 $
//
//  Dick Munroe (munroe@csworks.com) 28-Feb-2006
//      Initial version created
//
//  Dick Munroe (munroe@csworks.com) 14-Mar-2006
//      Add alternatePaymentStatus method.
//
//	Dick Munroe (munroe@csworks.com) 25-Mar-2006
//		Put in a notify_url field into the button so that
//		we get back to this script from the sandbox.
//

/**
 * @author Dick Munroe <munroe@csworks.com>
 * @copyright copyright @ 2006 by Dick Munroe, Cottage Software Works, Inc.
 * @license http://www.csworks.com/publications/ModifiedNetBSD.html
 * @version 1.0.2
 * @package dm.paypal
 * @example ./example.php
 *
 * Is an example of how to write Paypal IPN processors using the classes provided
 * by dm.paypal from phpclasses.org.  The overall process is pretty simple.
 *
 * 1. Create a class that extends paypalIPNBase.
 * 2. Override the following methods:
 *
 * 		A. preprocess - called before any $_POST processing has occurred.
 *      B. [optional] sourceNotEmpty - called if there is any data left in $_POST after extracting Paypal IPN data.
 *      C. alternatePaymentStatus - called if the IPN is not a completed payment.
 *      D. checkTransactionId - called to determine if the transaction Id is unique in your application.
 *      E. processPayment - called when the payment has been fully verified.
 *      F. postprocess - called after any/all processing has occurred.
 *
 * 3. Create your Purchasing environment.
 * 4. Configure Paypal to invoke your IPN page.
 * 5. Test, test, test.
 */

include_once("class.paypalIPNBase.php") ;
include_once("SDD/class.SDD.php") ;

/*
 * An example class to process IPNs in the context of the virtual_payment.php
 * invocation.
 */

class examplePaypalIPN extends paypalIPNBase
{
    var $m_localEmail = "" ;
    var $m_message = "" ;

    function examplePaypalIPN($theLocalEmail, $theReceiverEmail, $thePaypalURL = NULL, $theSandboxURL = NULL)
    {
	$this->m_localEmail = $theLocalEmail ;

	$this->paypalIPNBase($theReceiverEmail, $thePaypalURL, $theSandboxURL) ;
    }

    function preprocess(&$theSource)
    {
    }

    function postprocess(&$theIPN, $theStatus)
    {	
	if ($this->m_localEmail != '')
	{
	    mail($this->m_localEmail, "dm.paypal debugging", $this->m_message) ;
	}
	else
	{
		$fileName = "message_".date('Y_m_d_H_i_s').".html";
	    $f = fopen("./log/".$fileName, "w") ;
	    fwrite($f, $this->m_message) ;
	    fclose($f);
	    copy("./log/".$fileName, "./log/message_newest.html");
	}
    }

    function sourceNotEmpty(&$theIPN, &$theSource)
    {
		$theReturnStatus = parent::sourceNotEmpty($theIPN, $theSource) ;	
		return $theReturnStatus ;
    }
    
    function alternatePaymentStatus(&$theIPN)
    {
        /*
         * Indicate that the alternate payment status has been successfully
         * processed.
         */
        return true ;
    }

    /**
     * This is not normally overridden.  I do so here to provide additional information
     * in the context of the example.
     */

    function httpPost ($url, &$theIPN)
    {
		$theReturnStatus = parent::httpPost($url, $theIPN) ;
		
		$payment = new Payment();
		$paymentId = $theIPN->m_IPNData['item_number'];
		$paymentId = $payment->getAdapter()->quote($paymentId);
		$payment->update(array(
			'pgmDebugSent' 	=> 'STATUS:'. $theReturnStatus . '\n' . print_r($this->m_curl, true) 
		), 'pgmId = ' . $paymentId);
		
		return $theReturnStatus;
    }

    function checkTransactionId($theTransactionId)
    {
		return true ;
    }
	
    function validateItem(paypalIPNDATA &$theIPN)
    {
    	$this->m_message .= "validateItem: " ;    	
    	/**
    	 * Get payment from database, check if the 
    	 * pgm_gross is equal to payment_gross returned from paypal
    	 */
    	$payment = new Payment();
    	$data = $payment->fetchRow(array(
    		'pgmId' 	=> $theIPN->m_IPNData['item_number'],
    		'pgmGross' 	=> $theIPN->m_IPNData['payment_gross'],
    		'pgmStatus' => 'Pending'
    	));
    	if ($data)
    	{
    		$this->m_message .= "TRUE\n" ;
    		return true;
    	}
    	else	
    	{
    		$this->m_message .= "FALSE\n" ;
    		/**
    		 * UPdate status to Invalid
    		 */
    		$payment->update(array('pgmStatus' => 'InvalidGross'), 'pgmId = ' . $payment->getAdapter()->quote($theIPN->m_IPNData['item_number']));
    		return false;	
    	}
    }
    
    /**
     * Process payment
     *
     * @param paypalIPNData $theIPN
     * @return bool
     */
    public function processPayment(paypalIPNDATA &$theIPN)
    {
		$payment = new Payment();
		$paymentId = $theIPN->m_IPNData['item_number'];
		$paymentId = $payment->getAdapter()->quote($paymentId);
		$payment->update(array(
			'pgmStatus' => $theIPN->m_IPNData['payment_status'],
			'pgmDate' 	=> $theIPN->m_IPNData['payment_date'],
			'pgmGross' 	=> $theIPN->m_IPNData['payment_gross'],
			'pgmFee' 	=> $theIPN->m_IPNData['payment_fee'],
			'pgmDebugReceive' 	=> print_r($theIPN, true) 
		), 'pgmId = ' . $paymentId);
		
		$this->m_message .= "processPayment: DONE\n" ;
		return true ;
    }
}

if(count($_POST)>0)
{

    /*
     * Since this is a test environment, always use the receiver email provided from Paypal, and
     * write output to a log file (./log/message.html).  If you wish to have email sent to an
     * account instead, provide your email address as the first argument when creating the
     * example Paypal IPN object.
     */

    $ipn = new examplePaypalIPN("", $_POST['receiver_email']) ;
    $theStatus = $ipn->processNotification($_POST);
}
else
{
?>
<pre>
<!--
    This button was generated by the paypal sandbox and is specific to your particular site.  Generate a new one
    using the sandbox tools for your site and insert the html here.
-->

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="snm_1253418264_biz@gmail.com">
<input type="text" name="item_name" value="">
<input type="text" name="item_number" value="">
<input type="text" name="amount" value="10.00">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="bn" value="PP-BuyNowBF">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/x-click-but23.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
<pre>
	<?php
}

?>
